<?php
/**
 * @author Inhere
 * @version v1.0
 * Use : form
 * Date : 2014-7-10
 */
namespace ulue\libs\form;

class Form
{
    public $name = 'form';

    /**
     * @var AbstractField[]
     */
    protected $fields = [];

    /**
     * data validate rule settings
     * @var array
     */
    protected $rules = [];

    /**
     * bind to form's data
     * @var array
     */
    protected $data = [];

    /**
     * @var array
     */
    protected $attrs = [];

    /**
     * @var array
     */
    protected $errors = [];

    public function __construct($name=null)
    {
        if ( $name instanceof Model || $name instanceof GFormModel) {

        # 放到一个组里面 ... <input type="text" name="user[username]" id="user-username" />
        } else if ( is_string($name) )
        {
            $this->fieldArr = $name;
        }

    }

    public function setFields(array $fields)
    {
        $this->fields = (array)$fields;

        return $this;
    }

    public function addFields(array $fields)
    {
        if ($this->fields) {
            $this->fields = array_merge($this->fields, (array)$fields);
        } else {
            $this->fields = (array)$fields;
        }

        return $this;
    }

    public function addField($field , $fieldset='' , $group='')
    {

    }

    public function getField($name, $group=null)
    {

    }

    /**
     * [loadJson use json data]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function loadJson( $data )
    {

    }

    /**
     * [validate 验证]
     * @return [type] [description]
     */
    public function validate()
    {

    }

    public function render()
    {}

    /**
     * @return AbstractField
     */
    public function createField($type, $name,  array $attrs=[])
    {
        if ( !$this->supportedType($type) ) {
            # code...
        }

        $fieldClass = sprintf( __NAMESPACE__ . '\fields\%sField', $type);

    }

    public function supportedType($type)
    {
        $types = ['text','file','password','checkbox','radio','select','submit'];

        return isset($types[$type]);
    }

}
